package com.thx.tags;

import com.opensymphony.xwork2.util.ValueStack;
import com.thx.common.spring.BeanFactory;
import com.thx.dictionary.model.DictionaryValue;
import com.thx.dictionary.service.DictionaryValueManager;
import com.thx.org.model.Department;
import com.thx.org.service.DepartmentManager;
import com.thx.resource.model.Resource;
import com.thx.resource.service.ResourceManager;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.components.Component;

import java.io.Writer;
import java.util.List;

/**
 * select标签的类.
 * 
 * @author shiyan
 */
public class Property extends Component {

  private static final String TYPE_DEP = "dep";

  private static final String TYPE_DIC = "dic";

  private static final String TYPE_RESOURCE = "resource";

  private String value;

  private String type;

  private String dicCode;

  private String dicValueId;

  public Property(ValueStack stack) {
    super(stack);
  }

  @Override
  public boolean end(Writer writer, String body) {
    boolean result = super.start(writer);
    try {
      String text = "";
      if (TYPE_DIC.equals(type)) {
        DictionaryValueManager mgr =
            (DictionaryValueManager) BeanFactory.getBean("dictionaryValueManager");
        if (StringUtils.isNotBlank(value)) {
          DictionaryValue val = mgr.findByValueAndDicCode(value, dicCode);
          if (val != null) {
            text = val.getDicvText();
          }
        } else if (StringUtils.isNotBlank(dicValueId)) {
          List<DictionaryValue> vals = mgr.findByIDTAndDicCode(dicValueId, null, dicCode);
          if (vals != null && vals.size() > 0) {
            text = vals.get(0).getDicvText();
          }
        }
      } else if (TYPE_DEP.equals(type)) {
        DepartmentManager mgr = (DepartmentManager) BeanFactory.getBean("departmentManager");
        Department department = mgr.get(value);
        if (department != null) {
          text = department.getDepName();
        }
      } else if (TYPE_RESOURCE.equals(type)) {
        ResourceManager resourceManager = (ResourceManager) BeanFactory.getBean("resourceManager");
        Resource resource = resourceManager.get(value);
        if (resource != null) {
          text = resource.getName();
        }
      }
      writer.write(text);

    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return result;
  }


  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  public String getType() {
    return type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public String getDicCode() {
    return dicCode;
  }

  public void setDicCode(String dicCode) {
    this.dicCode = dicCode;
  }

  public String getDicValueId() {
    return dicValueId;
  }

  public void setDicValueId(String dicValueId) {
    this.dicValueId = dicValueId;
  }


}
